#include "softwarewidget.h"
#include <QPainter>
#include <QResizeEvent>
#include <QTimerEvent>
#include <QDateTime>

SoftwareWidget::SoftwareWidget(QWidget *parent)
    : QWidget(parent)
    , updateTimer(new QTimer(this))
{
    setAttribute(Qt::WA_OpaquePaintEvent, true);
    setAttribute(Qt::WA_NoSystemBackground, true);
    
    // 连接更新定时器
    connect(updateTimer, &QTimer::timeout, this, QOverload<>::of(&SoftwareWidget::update));
    updateTimer->setInterval(33); // 约30 FPS
}

SoftwareWidget::~SoftwareWidget()
{
}

void SoftwareWidget::setImage(const QImage &image)
{
    if (image.isNull())
        return;
        
    currentImage = image;
    updateScaledImage();
    
    if (!updateTimer->isActive()) {
        updateTimer->start();
    }
    
    update();
}

QImage SoftwareWidget::getImage() const
{
    return currentImage;
}

void SoftwareWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)
    
    QPainter painter(this);
    painter.fillRect(rect(), Qt::black);
    
    if (!scaledImage.isNull()) {
        QRect imageRect(scaledImage.rect());
        imageRect.moveCenter(rect().center());
        painter.drawImage(imageRect, scaledImage);
    } else if (!currentImage.isNull()) {
        // 如果还没有缩放图像，直接绘制原始图像
        QRect imageRect(currentImage.rect());
        imageRect.moveCenter(rect().center());
        painter.drawImage(imageRect, currentImage);
    }
}

void SoftwareWidget::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    updateScaledImage();
}

void SoftwareWidget::updateScaledImage()
{
    if (!currentImage.isNull() && !size().isEmpty()) {
        scaledImage = currentImage.scaled(size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    }
}